﻿using LSFTP.model;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace LSFTP
{
    public class SFTPClient : IFTP
    {

        #region 字段和属性
        
        private SftpClient sftp;

        public SftpClient GetSftp()
        {
            return sftp;
        }

        /// <summary>
        /// SFTP连接状态
        /// </summary>
        public bool Connected { get { return sftp.IsConnected; } }
        #endregion

        #region 构造函数

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="host">host IP</param>
        /// <param name="port">端口</param>
        /// <param name="username">用户名</param>
        /// <param name="passPhrase">密码短语</param>
        public SFTPClient(string host,int port,string username,string passPhrase)
        {
            sftp = new SftpClient(host, port, username, passPhrase);
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="host">host IP</param>
        /// <param name="port">端口</param>
        /// <param name="userName">用户名</param>
        /// <param name="passPhrase">密码短语</param>
        /// <param name="privateKeyFileName">私钥文件路径或内容</param>
        public SFTPClient(string host,int port,string userName,string passPhrase,string privateKeyFileName)
        {
            AuthenticationMethod[] auths = new AuthenticationMethod[1];
            if (string.IsNullOrEmpty(privateKeyFileName))
            {
                auths[0] = new PasswordAuthenticationMethod(userName, passPhrase);
            }
            else
            {
                try
                {
                    byte[] bs = null;
                    if(File.Exists(privateKeyFileName))
                    {
                        bs = Encoding.UTF8.GetBytes(File.ReadAllText(privateKeyFileName));
                    }
                    else if(privateKeyFileName.Contains("PRIVATE KEY"))
                    {
                        bs = Encoding.UTF8.GetBytes(privateKeyFileName);
                    }

                    if (null == bs) throw new Exception(string.Format("读取私钥异常，原因：未知私钥文件内容！"));

                    MemoryStream stream = new MemoryStream(bs);

                    PrivateKeyFile pkf = null;
                    if (string.IsNullOrEmpty(passPhrase))
                    {
                        pkf = new PrivateKeyFile(stream);
                    }
                    else
                    {
                        pkf = new PrivateKeyFile(stream, passPhrase);
                    }
                    auths[0] = new PrivateKeyAuthenticationMethod(userName, pkf);
                }
                catch(IOException exc)
                {
                    throw new Exception(string.Format("连接SFTP失败,原因：{0}",exc.Message));
                }
            }
            var connectionInfo = new ConnectionInfo(host, port, userName, auths);
            sftp = new SftpClient(connectionInfo);
        }
        #endregion

        #region 接口方法实现
        /// <summary>
        /// 连接FTP
        /// </summary>
        /// <returns>true成功</returns>
        public bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    sftp.Connect();
                }
                return true;
            }
            catch(Exception ex)
            {
                throw new Exception(string.Format("连接SFTP失败，原因：{0}", ex.Message));
            }
        }

        /// <summary>
        /// 断开FTP
        /// </summary> 
        public void Disconnect()
        {
            try
            {
                if(sftp != null && Connected)
                {
                    sftp.Disconnect();
                    //sftp.Dispose();
                }
            }
            catch(Exception ex)
            {
                throw new Exception(string.Format("端口SFTP失败，原因：{0}", ex.Message));
            }
        }

        /// <summary>
        /// 获取连接状态
        /// </summary>
        /// <returns></returns>
        public bool GetConnectStatus()
        {
            return Connected;
        }

        /// <summary>
        /// FTP上传文件
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="remotePath>远程路径</param>
        /// <returns>返回一个值，指示是否上传成功</returns>
        public bool Upload(string localPath, string remotePath)
        {
            try
            {
                string serverPath = remotePath.Replace(@"\", "/");
                if (!sftp.IsConnected)
                    Connect();

                FileInfo f = new FileInfo(localPath);
                using (var fileStream = new FileStream(localPath, FileMode.Open))
                {
                    if (!sftp.Exists(serverPath))
                        sftp.CreateDirectory(serverPath);

                    sftp.BufferSize = 4 * 1024;
                    sftp.UploadFile(fileStream, serverPath.TrimEnd('/') + "/" + f.Name, true, null);
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件上传失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 下载FTP文件
        /// </summary>
        /// <param name="remoteFile">远程路径</param>
        /// <param name="localPath">本地路径</param>
        /// <returns>返回一个值，指示是否下载成功</returns>
        public bool Download(string remoteFile, string localPath)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();
                string filePath = localPath.Substring(0, localPath.LastIndexOf('\\'));
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);

                using (Stream stream = File.Create(localPath))
                {
                    sftp.DownloadFile(remoteFile, stream);
                }

                //var byt = sftp.ReadAllBytes(remoteFile);
                //File.WriteAllBytes(localPath, byt);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        private void downloadCallback(ulong obj)
        {
            //Console.WriteLine("callback:" +  obj);
        }


        /// <summary>
        /// 下载FTP文件
        /// </summary>
        /// <param name="remoteFiles">远程路径列表</param>
        /// <param name="localPath">本地路径</param>
        /// <returns>返回一个值，指示是否下载成功</returns>
        public bool Download(List<FTPFileInfo> remoteFiles, string localPath)
        {
            try
            {
                if (remoteFiles == null || remoteFiles.Count == 0) return true;

                if (!sftp.IsConnected)
                    Connect();

                // 
                string rootPath = remoteFiles[0].FullName.Replace(remoteFiles[0].Name, "").Replace("//", "/").Replace("/","\\");
                if (rootPath.Equals("\\"))
                    rootPath = "\\\\\\\\\\\\\\\\\\\\\\\\";

                foreach (var item in remoteFiles)
                {
                    if (item.IsDirectory)
                    {
                        string lPath = localPath +"\\"+ item.Name;
                        if(!Directory.Exists(lPath))
                            Directory.CreateDirectory(lPath);
                        List<FTPFileInfo> list = GetFileInfoList(item.FullName,"*.*",true,false);

                        foreach (var item1 in list)
                        {
                            string llPath = (localPath + "\\" + item1.FullName.Replace("/", "\\").Replace(rootPath, "")).Replace("\\\\", "\\");
                            if (item1.IsDirectory)
                            {
                                if(!Directory.Exists(llPath))
                                    Directory.CreateDirectory(llPath);
                            }
                            else
                            {
                                string filePath = llPath.Replace(item1.Name, "");
                                if (!Directory.Exists(filePath))
                                    Directory.CreateDirectory(filePath);

                                using (Stream stream = File.Create(llPath))
                                {
                                    sftp.DownloadFile(item1.FullName, stream, downloadCallback);
                                }

                                //var byt = sftp.ReadAllBytes(item1.FullName);
                                //File.WriteAllBytes(llPath, byt);
                            }
                        }
                    }
                    else
                    {
                        if (!Directory.Exists(localPath))
                            Directory.CreateDirectory(localPath);

                        string localFile = localPath + "\\" + item.Name;

                        //var byt = sftp.ReadAllBytes(item.FullName);
                        //File.WriteAllBytes(localFile, byt);

                        using (Stream stream = File.Create(localFile))
                        {
                            sftp.DownloadFile(item.FullName, stream, downloadCallback);
                        }
                        //var byt = sftp.ReadAllBytes(item.FullName);
                        //using (var fs = new FileStream(localPath, FileMode.CreateNew))
                        //{
                        //    var stream = new MemoryStream(byt);
                        //    byte[] bytes = new byte[1024];
                        //    int count = 0;
                        //    int readCount = 0;
                        //    while ((count = stream.Read(bytes, 0, bytes.Length)) > 0)
                        //    {
                        //        fs.Write(bytes, 0, count);
                        //        fs.Flush();
                        //        readCount += count;
                        //    }
                        //    stream.Close();
                        //    var Count = readCount;
                        //}
                    }
                }


                
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }


        /// <summary>
        /// 重命名FTP文件
        /// </summary>
        /// <param name="oldFilePath">旧远程路径</param>
        /// <param name="newFilePath">新远程路径</param>
        /// <returns>返回一个值，指示是否重命名成功</returns>
        public bool Rename(string oldFilePath, string newFilePath)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();

                string serverPath = newFilePath.Replace(@"\", "/");
                string directoryPath = serverPath.Substring(0, serverPath.LastIndexOf('/'));
                if (string.IsNullOrEmpty(directoryPath))
                {
                    directoryPath = "/";
                }
                if (!sftp.Exists(directoryPath))
                    sftp.CreateDirectory(directoryPath);

                sftp.RenameFile(oldFilePath, newFilePath);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件重命名失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 删除FTP文件
        /// </summary>
        /// <param name="remoteFile">远程文件路径</param>
        /// <returns>返回一个值，指示是否删除成功</returns>
        public bool DeleteFile(string remoteFile)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();
                if (sftp.Exists(remoteFile))
                    sftp.Delete(remoteFile);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件删除失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="dirName">远程文件夹路径</param>
        /// <returns>返回一个值，指示是否删除成功</returns>
        public bool DeleteDirectory(string dirName)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();

                if (sftp.Exists(dirName))
                {
                    List<string> fileList_pv = new List<string>();
                    GetFileList(sftp, dirName, "*.*", true, ref fileList_pv);
                    fileList_pv.Sort((x, y) => -x.Length.CompareTo(y.Length));
                    foreach (var file in fileList_pv)
                    {
                        sftp.Delete(file);
                    }

                    //无法移除根目录
                    if (!sftp.WorkingDirectory.Equals(dirName))
                        sftp.DeleteDirectory(dirName);
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件夹删除失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 获取FTP服务根目录文件列表
        /// </summary>
        /// <returns>返回文件名列表</returns>
        public List<string> GetFileList()
        {
            return GetFileList(string.Empty);
        }

        /// <summary>
        /// 获取FTP文件列表
        /// </summary>
        /// <param name="remotePath"></param>
        /// <returns>返回文件名列表</returns>
        public List<string> GetFileList(string remotePath)
        {
            string serverPath = "/";
            if (!string.IsNullOrEmpty(remotePath))
                serverPath = remotePath;
            return GetFileList(serverPath, "*.*");
        }

        /// <summary>
        /// 获取固定后缀的FTP文件列表
        /// </summary>
        /// <param name="remotePath">远程文件夹路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <returns>返回文件名列表</returns>
        public List<string> GetFileList(string remotePath, string fileSuffix)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();
                var files = sftp.ListDirectory(remotePath);
                var objList = new List<string>();

                string suffix_ = string.Empty;
                if (!string.IsNullOrEmpty(fileSuffix) && fileSuffix.Contains("."))
                    suffix_ = fileSuffix.Substring(fileSuffix.LastIndexOf('.'));

                foreach (var file in files)
                {
                    string name = file.Name;
                    if (!string.IsNullOrEmpty(suffix_) && !".*".Equals(suffix_))
                    {
                        string gSuffix = string.Empty;
                        if (name.Contains("."))
                            gSuffix = name.Substring(name.LastIndexOf('.'));

                        if (!string.IsNullOrEmpty(gSuffix) && gSuffix.Equals(suffix_))
                        {
                            objList.Add(name);
                        }
                    }
                    else
                    {
                        objList.Add(name);
                    }
                }
                return objList;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 深层遍历文件夹，获取FTP文件列表
        /// </summary>
        /// <param name="remotePath">远程文件夹路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="deep">遍历获取</param>
        /// <returns>返回文件名列表</returns>
        public List<string> GetFileList(string remotePath, string fileSuffix, bool deep)
        {
            try
            {
                string serverPath = remotePath.Replace(@"\", "/");
                if (!sftp.IsConnected)
                    Connect();
                var files = sftp.ListDirectory(serverPath);
                var objList = new List<string>();

                string suffix_ = string.Empty;
                if (!string.IsNullOrEmpty(fileSuffix) && fileSuffix.Contains("."))
                    suffix_ = fileSuffix.Substring(fileSuffix.LastIndexOf('.'));

                foreach (var file in files)
                {
                    string name = file.Name;

                    //排除目录根节点
                    if (name.EndsWith("."))
                        continue;

                    if (!string.IsNullOrEmpty(suffix_) && !".*".Equals(suffix_))
                    {
                        string gSuffix = string.Empty;
                        if (name.Contains("."))
                            gSuffix = name.Substring(name.LastIndexOf('.'));

                        if (!string.IsNullOrEmpty(gSuffix) && gSuffix.Equals(suffix_))
                        {
                            objList.Add(serverPath.TrimEnd('/') + "/" + name);
                        }
                    }
                    else
                    {
                        objList.Add(serverPath.TrimEnd('/') + "/" + name);
                    }

                    if (file.IsDirectory && deep && !name.Contains("."))
                        GetFileList(sftp, serverPath.TrimEnd('/') + "/" + name, fileSuffix, deep, ref objList);
                }
                return objList;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 深度获取文件列表
        /// </summary>
        /// <param name="sftp"></param>
        /// <param name="remotePath"></param>
        /// <param name="fileSuffix"></param>
        /// <param name="deep"></param>
        /// <param name="fileList"></param>
        /// <returns></returns>
        private void GetFileList(SftpClient sftp_pv, string remotePath, string fileSuffix, bool deep, ref List<string> fileList_pv)
        {
            string serverPath = remotePath.Replace(@"\", "/");

            var files = sftp.ListDirectory(serverPath);
            string suffix_ = string.Empty;
            if (!string.IsNullOrEmpty(fileSuffix) && fileSuffix.Contains("."))
                suffix_ = fileSuffix.Substring(fileSuffix.LastIndexOf('.'));

            foreach (var file in files)
            {
                string name = file.Name;

                //排除目录根节点
                if (name.EndsWith("."))
                    continue;

                if (!string.IsNullOrEmpty(suffix_) && !".*".Equals(suffix_))
                {
                    string gSuffix = string.Empty;
                    if (name.Contains("."))
                        gSuffix = name.Substring(name.LastIndexOf('.'));

                    if (!string.IsNullOrEmpty(gSuffix) && gSuffix.Equals(suffix_))
                    {
                        fileList_pv.Add(serverPath.TrimEnd('/') + "/" + name);
                    }
                }
                else
                {
                    fileList_pv.Add(serverPath.TrimEnd('/') + "/" + name);
                }

                //if (file.IsDirectory && deep && !name.Contains("."))
                if (file.IsDirectory && deep)
                    GetFileList(sftp_pv, serverPath.TrimEnd('/') + "/" + name, fileSuffix, deep, ref fileList_pv);
            }
        }

        /// <summary>
        /// 获取服务目录列表
        /// </summary>
        /// <param name="remoteFolder"></param>
        /// <returns>返回目录名列表</returns>
        public List<string> GetDirectoryList(string remoteFolder)
        {
            try
            {
                string serverPath = "/";
                if (!string.IsNullOrEmpty(remoteFolder))
                    serverPath = remoteFolder.Replace(@"\", "/"); ;

                if (!sftp.IsConnected)
                    Connect();
                var files = sftp.ListDirectory(serverPath);
                var objList = new List<string>();

                foreach (var file in files)
                {
                    string name = file.Name;

                    //排除目录根节点
                    if (name.EndsWith("."))
                        continue;

                    if (file.IsDirectory)
                        objList.Add(serverPath.TrimEnd('/') + "/" + name);
                }
                return objList;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 移动FTP文件
        /// </summary>
        /// <param name="oldRemotePath">旧远程文件路径</param>
        /// <param name="newRemotePath">新远程文件路径</param>
        /// <returns>返回一个值，指示是否移动成功</returns>
        public bool Move(string oldRemotePath, string newRemotePath)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();

                string serverPath = newRemotePath.Replace(@"\", "/");
                string directoryPath = serverPath.Substring(0, serverPath.LastIndexOf('/'));
                if (!sftp.Exists(directoryPath))
                    sftp.CreateDirectory(directoryPath);

                sftp.RenameFile(oldRemotePath, newRemotePath);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件移动失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 检查当前路径上是否存在某个文件
        /// </summary>
        /// <param name="remoteFile">要检查的文件名</param>
        /// <returns>返回一个值,指示要检查的文件是否存在</returns>
        public bool CheckFileExist(string remoteFile)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();
                sftp.Exists(remoteFile);
                return true;
            }
            catch(Exception ex)
            {
                throw new Exception(string.Format("SFTP判断文件是否存在失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 在当前目录下创建文件夹
        /// </summary>
        /// <param name="dirName">文件夹名称</param>
        /// <returns>返回一个值,指示是否创建成功</returns>
        public bool MakeDirectory(string dirName)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();
                if (!sftp.Exists(dirName))
                    sftp.CreateDirectory(dirName);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP创建文件夹失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 在当前目录下创建文件夹
        /// </summary>
        /// <param name="path">远程路径</param>
        /// <param name="name">文件名</param>
        /// <returns>返回一个值,指示是否创建成功</returns>
        public bool MakeDirectory(string path ,string name)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();
                sftp.ChangeDirectory(path);

                if (!sftp.Exists(name))
                    sftp.CreateDirectory(name);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP创建文件夹失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 获取最后修改时间
        /// </summary>
        /// <param name="remoteFile">远程文件名</param>
        /// <returns>返回最后修改时间</returns>
        public DateTime GetLastWriteTime(string remoteFile)
        {
            try
            {

                if (!sftp.IsConnected)
                    Connect();
                return sftp.GetLastWriteTime(remoteFile);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP获取文件修改时间失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 获取FTP服务根目录文件列表
        /// </summary>
        /// <returns>返回文件详细信息列表</returns>
        public List<FTPFileInfo> GetFileInfoList()
        {
            return GetFileInfoList(string.Empty);
        }

        /// <summary>
        /// 获取FTP文件列表
        /// </summary>
        /// <param name="remotePath"></param>
        /// <returns>返回文件详细信息列表</returns>
        public List<FTPFileInfo> GetFileInfoList(string remotePath)
        {
            string serverPath = "/";
            if (!string.IsNullOrEmpty(remotePath))
                serverPath = remotePath;
            return GetFileInfoList(serverPath, "*.*");
        }

        /// <summary>
        /// 获取固定后缀的FTP文件列表
        /// </summary>
        /// <param name="remotePath">远程文件夹路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <returns>返回文件详细信息列表</returns>
        public List<FTPFileInfo> GetFileInfoList(string remotePath, string fileSuffix)
        {
            try
            {
                if (!sftp.IsConnected)
                    Connect();
                var files = sftp.ListDirectory(remotePath);
                var objList = new List<FTPFileInfo>();

                string suffix_ = string.Empty;
                if (!string.IsNullOrEmpty(fileSuffix) && fileSuffix.Contains("."))
                    suffix_ = fileSuffix.Substring(fileSuffix.LastIndexOf('.'));

                foreach (var file in files)
                {
                    string name = file.Name;
                    if (!string.IsNullOrEmpty(suffix_) && !".*".Equals(suffix_))
                    {
                        string gSuffix = string.Empty;
                        if (name.Contains("."))
                            gSuffix = name.Substring(name.LastIndexOf('.'));

                        if (!string.IsNullOrEmpty(gSuffix) && gSuffix.Equals(suffix_))
                        {
                            objList.Add(new FTPFileInfo(file));
                        }
                    }
                    else
                    {
                        objList.Add(new FTPFileInfo(file));
                    }
                }
                return objList;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
            finally
            {
                //Disconnect();
            }
        }

        /// <summary>
        /// 深层遍历文件夹，获取FTP文件列表
        /// </summary>
        /// <param name="remotePath">远程文件夹路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="deep">遍历获取</param>
        /// <param name="isDisConnect">是否关闭连接</param>
        /// <returns>返回文件详细信息列表</returns>
        public List<FTPFileInfo> GetFileInfoList(string remotePath, string fileSuffix, bool deep,bool isDisConnect=true)
        {
            try
            {
                string serverPath = remotePath.Replace(@"\", "/");
                if (!sftp.IsConnected)
                    Connect();
                var files = sftp.ListDirectory(serverPath);
                var objList = new List<FTPFileInfo>();

                string suffix_ = string.Empty;
                if (!string.IsNullOrEmpty(fileSuffix) && fileSuffix.Contains("."))
                    suffix_ = fileSuffix.Substring(fileSuffix.LastIndexOf('.'));

                foreach (var file in files)
                {
                    string name = file.Name;

                    //排除目录根节点
                    if (name.EndsWith("."))
                        continue;

                    if (!string.IsNullOrEmpty(suffix_) && !".*".Equals(suffix_))
                    {
                        string gSuffix = string.Empty;
                        if (name.Contains("."))
                            gSuffix = name.Substring(name.LastIndexOf('.'));

                        if (!string.IsNullOrEmpty(gSuffix) && gSuffix.Equals(suffix_))
                        {
                            objList.Add(new FTPFileInfo(file));
                        }
                    }
                    else
                    {
                        objList.Add(new FTPFileInfo(file));
                    }

                    if (file.IsDirectory && deep && !name.Contains("."))
                        GetFileList(sftp, serverPath.TrimEnd('/') + "/" + name, fileSuffix, deep, ref objList);
                }
                return objList;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
            finally
            {
                if (isDisConnect)
                {
                    //Disconnect();
                }
            }
        }

        /// <summary>
        /// 深度获取文件列表
        /// </summary>
        /// <param name="sftp"></param>
        /// <param name="remotePath"></param>
        /// <param name="fileSuffix"></param>
        /// <param name="deep"></param>
        /// <param name="fileList"></param>
        /// <returns></returns>
        private void GetFileList(SftpClient sftp_pv, string remotePath, string fileSuffix, bool deep, ref List<FTPFileInfo> fileList_pv)
        {
            string serverPath = remotePath.Replace(@"\", "/");

            var files = sftp.ListDirectory(serverPath);
            string suffix_ = string.Empty;
            if (!string.IsNullOrEmpty(fileSuffix) && fileSuffix.Contains("."))
                suffix_ = fileSuffix.Substring(fileSuffix.LastIndexOf('.'));

            foreach (var file in files)
            {
                string name = file.Name;

                //排除目录根节点
                if (name.EndsWith("."))
                    continue;

                if (!string.IsNullOrEmpty(suffix_) && !".*".Equals(suffix_))
                {
                    string gSuffix = string.Empty;
                    if (name.Contains("."))
                        gSuffix = name.Substring(name.LastIndexOf('.'));

                    if (!string.IsNullOrEmpty(gSuffix) && gSuffix.Equals(suffix_))
                    {
                        fileList_pv.Add(new FTPFileInfo(file));
                    }
                }
                else
                {
                    fileList_pv.Add(new FTPFileInfo(file));
                }

                if (file.IsDirectory && deep && !name.Contains("."))
                    GetFileList(sftp_pv, serverPath.TrimEnd('/') + "/" + name, fileSuffix, deep, ref fileList_pv);
            }
        }

        #endregion
    }
}
